package org.fengling.readingplatform.manager.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.fengling.readingplatform.manager.mapper.NovelMapper;
import org.fengling.readingplatform.manager.service.NovelService;
import org.fengling.readingplatform.model.dto.novel.NovelDto;
import org.fengling.readingplatform.model.entity.novel.Novel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NovelServiceImpl implements NovelService {

    public static final String CACHA_KEY_NOVELINFO = "novelInfo:readingplatform:";

    @Autowired
    private NovelMapper novelMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    // 小说添加方式
    @Override
    public void save(Novel novel) {
        try {
            novelMapper.save(novel);
        } catch (Exception e) {
            // 处理异常，可能是插入失败
            System.out.println("Failed to insert novel: " + e.getMessage());
        }
        // redis缓存key
        String key = CACHA_KEY_NOVELINFO + novel.getId();

        redisTemplate.opsForValue().set(key, novel);
    }

    // 小说分页查询方法
    @Override
    public PageInfo<Novel> findByPage(NovelDto novelDto, Integer current, Integer limit) {
        // 设置分页参数
        PageHelper.startPage(current, limit);
        // 根据条件查询所有数据
        List<Novel> list = novelMapper.findByPage(novelDto);
        // 封装pageInfo对象
        PageInfo<Novel> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    // 小说删除方法
    @Override
    public void deleteById(Long id) {
        novelMapper.delete(id);
    }

    // 小说更新的方法
    @Override
    public void updateNovel(Novel novel) {
        novelMapper.updateNovel(novel);
        redisTemplate.delete(CACHA_KEY_NOVELINFO + novel.getId());
    }

    // 查询小说标号的方法
    @Override
    public Long findNovelId(NovelDto novelDto) {
        String title = novelDto.getTitle();
        return novelMapper.findNovelId(title);
    }
}
